package com.vf.cloud.server.relay;

import com.jfinal.kit.StrKit;
import com.vf.cloud.common.constant.Cache;


import com.alibaba.fastjson.JSONObject;
import com.vf.cloud.common.util.SpringContextHolder;
import com.vf.cloud.common.vo.RelayVo;
import com.vf.cloud.server.relay.server.TurnServer;
import com.vf.cloud.server.relay.server.StunServer;

public class RelayServer {

	private static volatile RelayServer INSYANCE;

	private TurnServer turn;
	
	private StunServer stun;
	
	
	

	private RelayServer() {
		turn = SpringContextHolder.getBean(TurnServer.class);
		stun= SpringContextHolder.getBean(StunServer.class);
	}

	public static RelayServer getInstance() {
		if (null == INSYANCE) {
			synchronized (RelayServer.class) {
				if (null == INSYANCE) {
					INSYANCE = new RelayServer();
				}
			}
		}
		return INSYANCE;
	}

	public void run(RelayVo config) {
		Cache.relay=config;
		if(turn!=null) {
			turn.run();
		}
		
		if(stun!=null) {
			stun.run();
		}
	}
	
	public void restart(RelayVo config) {
		Cache.relay=config;
		if(stun!=null) {
			stun.run();
		}
		if(turn!=null) {
			turn.run();
		}
		
	}
	
	public void stop() {
		if(turn!=null) {
			turn.stop();
		}
		
		if(stun!=null) {
			stun.stop();
		}
		
	}
	
	public boolean verify(JSONObject object) {

		if (object == null) {
			return false;
		}
		
		if(!object.containsKey("ip") || StrKit.isBlank(object.getString("ip"))) {
			return false;
		}
		if(!object.containsKey("stunPort") || StrKit.isBlank(object.getString("stunPort"))) {
			return false;
		}
		if(!object.containsKey("turnPort") || StrKit.isBlank(object.getString("turnPort"))) {
			return false;
		}
		return true;
	}
	

}

